from flask import Blueprint
from flask import render_template
from flask import request
from flask import jsonify
from admin.core.auth import permission_check
# from admin.core.auth import verify_user
# from admin.core.auth import generate_token_by_user
# from admin.core.auth import destory_token
# from admin.core.auth import get_buttons_by_token
from admin.core.user import get_user_by_username
from admin.core.user import add_user
from admin.core.user import get_user_dic
import json
from models.entity.role import Role
from models.entity.token import Token

mod = Blueprint("test1", __name__, template_folder="templates", static_folder="static")

@mod.route("/test1/",methods=["GET"])
@permission_check
def test():
    return render_template("test1.html")

@mod.route("/add_user/",methods=["POST"])
def add_user_interface():
    # request: json
    # {
    #       username:"username"(必填),
    #       password:"password"(必填),
    #       email:"email",
    #       phone_number:"phone_number",
    #       safe_code:"safe_code",
    #       department_id:department_id,
    #       organization_id:organization_id(必填),
    #       roles: [role_id_1,role_id_2,...]
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                        "success":0,
                        "error_code":-1,
                        "error_msg":"json format error",
                }
        return jsonify(error_msg)
    try:
        username=data["username"]
        password=data["password"]
        roles=data["roles"]
        organization_id=data["organization_id"]
    except:
        error_msg={
                        "success":0,
                        "error_code":-2,
                        "error_msg":"key of json is not complete"
                }
        return jsonify(error_msg)
    in_dic={}
    in_dic["username"]=username
    in_dic["password"]=password
    if "email" in data:
        in_dic["email"]=data["email"]
    if "phone_number" in data:
        in_dic["phone_number"]=data["phone_number"]
    if "safe_code" in data:
        in_dic["safe_code"]=data["safe_code"]
    if "department_id" in data:
        in_dic["department_id"]=data["department_id"]
    if "organization_id" in data:
        in_dic["organization_id"]=data["organization_id"]
    in_dic["roles"]=[]
    for item in roles:
        the_role=Role.query.filter_by(id=item).first()
        in_dic["roles"].append(the_role)
    ret_user=add_user(in_dic)
    if isinstance(ret_user,int):
        print("add_user_interface error")
        return -1
    return jsonify(get_user_dic(ret_user))

@mod.route("/get_token/",methods=["POST"])
def get_token_interface():
    # 获取访问token
    # request: json
    # {
    #       username:"username",
    #       password:"password"
    # }
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[{
    #               username:"username",
    #               token:"token"
    #            }]
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                        "success":0,
                        "error_code":-1,
                        "error_msg":"json format error",
                        "data":[]
                }
        return jsonify(error_msg)
    try:
        username=data["username"]
        password=data["password"]
    except:
        error_msg={
                        "success":0,
                        "error_code":-2,
                        "error_msg":"json key is not complete",
                        "data":[]
                }
        return jsonify(error_msg)
    if username is None or username=="":
        error_msg={
                        "success":0,
                        "error_code":-3,
                        "error_msg":"username cannot be empty",
                        "data":[]
                }
        return jsonify(error_msg)
    if password is None or password=="":
        error_msg={
                        "success":0,
                        "error_code":-4,
                        "error_msg":"password cannot be empty",
                        "data":[]
                }
        return jsonify(error_msg)
    ret=verify_user(username,password)
    if ret==-1:
        error_msg={
                        "success":0,
                        "error_code":-5,
                        "error_msg":"user not exist",
                        "data":[]
                }
        return jsonify(error_msg)
    if ret==-2:
        error_msg={
                        "success":0,
                        "error_code":-6,
                        "error_msg":"password is not correct",
                        "data":[]
                }
        return jsonify(error_msg)
    if ret==0:
        rdic={
                        "success":1,
                        "error_code":None,
                        "error_msg":None,
                        "data":[]
                }
        rdic["data"].append({})
        rdic["data"][0]["username"]=username
        the_user=get_user_by_username(username)
        the_token=generate_token_by_user(the_user).token
        if the_token==-1 or the_token==-2:
            error_msg={
                            "success":0,
                            "error_code":-7,
                            "error_msg":"generate_token_by_user error",
                            "data":[]
                    }
            return jsonify(error_msg)
        rdic["data"][0]["token"]=the_token.token
        return jsonify(rdic)
    token_list=Token.query.filter_by(user_id=the_user.id).all()
    for item in token_list:
        ret=destory_token(item)
        if ret!=0:
            error_msg={
                                            "success":0,
                                            "error_code":-8,
                                            "error_msg":"destory token error",
                                            "data":[]
                                    }
            return jsonify(error_msg)
    error_msg={
                    "success":0,
                    "error_code":-8,
                    "error_msg":"unknow error",
                    "data":[]
            }
    return jsonify(error_msg)

@mod.route("/get_buttons_by_token/",methods=["POST"])
def get_buttons_by_token_interface():
    # request: json
    # {
    #       token:"token"
    # }
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[button_id_1,button_id_2,...]
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                                        "success":0,
                                        "error_code":-1,
                                        "error_msg":"json format error",
                                        "data":[]
                                }
        return jsonify(error_msg)
    if not "token" in data:
        error_msg={
                                        "success":0,
                                        "error_code":-1,
                                        "error_msg":"key of json is not complete",
                                        "data":[]
                                }
        return jsonify(error_msg)
    token=data["token"]
    the_token=Token.query.filter_by(token=token).first()
    if not the_token:
        error_msg={
                                        "success":0,
                                        "error_code":-2,
                                        "error_msg":"token is not exist",
                                        "data":[]
                                }
        return jsonify(error_msg)
    button_list=get_buttons_by_token(the_token)
    rlist=[]
    for item in button_list:
        rlist.append(item.id)
    rdic={
                        "success":1,
                        "error_code":None,
                        "error_msg":None,
                        "data":[]
                }
    rdic["data"]=rlist
    return jsonify(rdic)

@mod.route("/get_modules_and_buttons_by_token/",methods=["POST"])
def get_modules_and_buttons_by_token_interface():
    # request: json
    # {
    #       token: "token"
    # }
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[]
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                                        "success":0,
                                        "error_code":-1,
                                        "error_msg":"json format error"
                                }
        return jsonify(error_msg)
    if not "token" in data:
        error_msg={
                                        "success":0,
                                        "error_code":-2,
                                        "error_msg":"key of json is not complete"
                                }
        return jsonify(error_msg)
    the_token=Token.query.filter_by(token=data["token"]).first()
    if not the_token:
        error_msg={
                                        "success":0,
                                        "error_code":-3,
                                        "error_msg":"token is not exist"
                                }
        return jsonify(error_msg)
    button_list=get_buttons_by_token(the_token)
    module_set=set()
    for item in button_list:
        module_set.add(item.module_id)
    rdic={
                        "success":1,
                        "error_code":None,
                        "error_msg":None,
                }
    rdic["data"]=list(module_set)
    return jsonify(rdic)
